#! /usr/bin/env python
"""Skeleton project file mainloop for new OLPCGames users"""
import logging
import copy
log = logging.getLogger('XOMuncher run')
log.setLevel(logging.DEBUG)

import olpcgames, pygame 
from olpcgames import pausescreen, svgsprite
from gettext import gettext as _ 

from random import Random
rand = Random()

import gamestate
import board
#import comm   # not used yet networking class

def main():
    """The mainloop which is specified in the activity.py file    
    "main" is the assumed function name
    """
    size = (800,600)
    if olpcgames.ACTIVITY:
        size = olpcgames.ACTIVITY.game_size
    screen = pygame.display.set_mode(size)

    bgcolor = (190,190,190) # Background color - gray for now
    fgcolor = (0,0,0) # Foreground color - black for now
    
    #Intialize game board
    gstate = gamestate.GameState()
    gstate.GameBoard = board.Board(5,5)
    levelid = rand.choice(gstate.GameBoard.GetBoardIDs())
    gstate.GameBoard.LoadBoardID(levelid)
    gstate.GameBoard.CreateBoard(70) #create with 70% allowed
    
    #Add a player
    gstate.PlayerList.AddPlayer()
    pname = gstate.PlayerList[gstate.PlayerList.INDEX_NAME]
    gstate.PlayerList.SetX(pname, 0)
    gstate.PlayerList.SetY(pname, 0)
    
    pygame.init()
    munch_sound = pygame.mixer.Sound("sounds/chomp.wav")
            
    clock = pygame.time.Clock()
    running = True

    while running:
        screen.fill(bgcolor) 
        milliseconds = clock.tick(25) # Maximum number of frames per second
        
        # Event-management loop with support for pausing after X seconds (30 here)
        # queues events up until the pause screen shows in 30 seconds
        events = pausescreen.get_events(30)
        # Now the main event-processing loop
        if events:
            flag=1
            for event in events:
                if event.type == pygame.MOUSEMOTION:
                    continue
                log.debug( "Event: %s", event )
                #print event
                if event.type == pygame.QUIT:
                    running = False
                # Process keyboard input
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        running = False                         
                    elif event.key in (pygame.K_UP, pygame.K_KP8):
                        print "Move Up"
                        gstate.MovePlayer(pname,gstate.UP)
                        flag=2
                    elif event.key in (pygame.K_DOWN, pygame.K_KP2):
                        print "Move Down"
                        gstate.MovePlayer(pname,gstate.DOWN)
                        flag=2
                    elif event.key in (pygame.K_LEFT, pygame.K_KP4):
                        print "Move Left"
                        gstate.MovePlayer(pname,gstate.LEFT)
                        flag=2
                    elif event.key in (pygame.K_RIGHT, pygame.K_KP6):
                        print "Move Right"
                        gstate.MovePlayer(pname,gstate.RIGHT)
                        flag=2
                    elif event.key in (pygame.K_SPACE, pygame.K_KP1, pygame.K_KP3, pygame.K_KP7, pygame.K_KP9):
                        print "Munch"       
                        munch_sound.play(0)                      
                        gstate.Munch(pname)

                        # redraw board twice so that there isn't a problem with redraw
                        # draw once here with flag 1... draw it again with flag=2 below
                        gstate.drawBoard(screen, fgcolor, bgcolor, 1)

                        flag=2
                    #comm.SendAll(gstate)                        
                # Process toolbar events
                elif event.type == pygame.USEREVENT:
                    if event.action == 'new':
                        print "New Game"
                        gstate.GameBoard = board.Board(5,5)
                        levelid = rand.choice(gstate.GameBoard.GetBoardIDs())
                        gstate.GameBoard.LoadBoardID(levelid)
                        gstate.GameBoard.CreateBoard(70)
                        gstate.cached_top = None
                        flag=1
                    else:
                        print "Unknown user event action:", event.action
                        
                # Process network events
                #comm.HandleEvent(event, gstate)
                
                #Check done
                if gstate.GameBoard.CheckDone():
                    gstate.GameBoard = board.Board(5,5)
                    levelid = rand.choice(gstate.GameBoard.GetBoardIDs())
                    gstate.GameBoard.LoadBoardID(levelid)
                    gstate.GameBoard.CreateBoard(70)
                    gstate.PlayerList.AddLives(pname, 1)
                    gstate.cached_top = None
                    flag=2 # setting this to 1 will NOT redraw the top and circle

                    # redraw board twice so that there isn't a problem with redraw
                    # draw once here with flag 1... draw it again with flag=2 below
                    gstate.drawBoard(screen, fgcolor, bgcolor, 1)

                    break # unqueue the events
                if gstate.PlayerList.GetDead(pname):
                    gstate = gamestate.GameState()
                    gstate.GameBoard = board.Board(5,5)
                    levelid = rand.choice(gstate.GameBoard.GetBoardIDs())
                    gstate.GameBoard.LoadBoardID(levelid)
                    gstate.GameBoard.CreateBoard(70)
                    gstate.PlayerList.AddPlayer()
                    pname = gstate.PlayerList[gstate.PlayerList.INDEX_NAME]
                    gstate.PlayerList.SetX(pname, 0)
                    gstate.PlayerList.SetY(pname, 0)                    
                    gstate.cached_top = None
                    flag=2 # setting this to 1 will NOT redraw the top and circle

                    # redraw board twice so that there isn't a problem with redraw
                    # draw once here with flag 1... draw it again with flag=2 below
                    gstate.drawBoard(screen, fgcolor, bgcolor, 1)

                    break # unqueue the events
            # Redraw            
            gstate.drawBoard(screen, fgcolor, bgcolor, flag)
            pygame.display.flip()              
            #clock.tick(20) # Don't animate faster than 20 fps
    pygame.quit()
    
if __name__ == "__main__":
    logging.basicConfig()
    main()
